use std::str::from_utf8;
pub fn string_usage()
{
    //静态数据区
    let index = 2;
    let s1:&'static str = "I am a superman.";
    //heap
    let s2:String = s1.to_string();
    let s3:& String = &s2;
    let s4:&str = &s2[..];
    let s5:&str = &s2[..index];

    println!("{:?}\n{}",s5,s5);

    let str = "I am a superhero".to_string();
    let a_slice: &str = &str[1..4];
    let another_string = a_slice.to_string();   //这里还是堆区域中的切片内容的借用
    let reference_string = a_slice.to_owned();

    let s = String::from("hello");
    assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());   //比较两个字节串是否相等

}
//字节串的综合应用
pub fn byte_string()
{
    let foo = |para:&str| {
        println!("{para}");
        //return para;
    };
    let a_vec = vec![1,2,3,4,5];
    assert_eq!(&[1,2,3,4,5],a_vec.as_slice());  //vec的u8方法as_slice()与String的as_str()方法对应

    let s = String::from("I am a superman.");
    foo(&s);
    let s1 = "I am a superman.";
    foo(s1);

    let s2 = &s;
    let s3: &str = &s;
    foo(s3);

    //根据不同的引用类型进行调用
    let v:Vec<u32> = vec![1,2,3,4,5];


    let a_slice = v.as_slice();

    //闭包函数的定义
    let foo_pak = |val: &[u32]| -> Vec<u32> {
        println!("Debug{:?}",val);
        val.to_vec()
    };

    let vec_result = foo_pak(a_slice);
    println!("val.to_vec() {:?}",vec_result);

    //字节串转换成字符串

    //let utf8str:Vec<u8> = String::from_utf8(bytestr);

    let vecu8:Vec<u8> = vec![2,3,3,45];
    let String_value = String::from_utf8(vecu8);

    println!("Debug {:?}",String_value);

}

pub fn string_to_bytestr() {
    /*
    类型有个 chars() 函数，可以用来把字符串转换为一个迭代器，
    迭代器是一种通用的抽象，就是用来按顺序安全迭代的
    */
    let s = String::from("中国你好");
    let char_vec: Vec<char> = s.chars().collect();
    println!("{:?}",char_vec);

    for ch in s.chars() {
        println!("{ch}");
    }
}

//将字符串转换到任意的Rust类型,只要这个类型实现了FromStr这个Trait
//https://doc.rust-lang.org/std/str/trait.FromStr.html#implementors
//上面链接可以查看rust中有哪些内置的类型可以实现转换 （字符串-> 对应的数据类型）
pub fn parse_usage() {
    let a = "10".parse::<u32>();
    let aa: u32 = "123".parse().unwrap(); //转换失败直接panic
    println!("{:?}",a); //Debug会打印一个ok

    let a = "50.6".parse::<f32>();

    let a = "true".parse::<bool>();
    let a = "a".parse::<char>();

    let a = "192.168.1.100".parse::<std::net::IpAddr>();
    println!("{:?}",a);

    let a_string = String::from("A str");
    let typechar = a_string.chars();

    let arr = [1, 3, 5, 7, 9];
    let part = &arr[0..3];
    for i in part.iter() {
        println!("{}", i);
    }
}
